{include "INC_header.html" title="账户管理"}
<div id="app-outlet" class="app-outlet padding">
    <!-- ant-design 应用需要配置 -->
    <a-config-provider :locale="config.locale" :theme="config.theme">
        <div class="app-container">
            <!-- 搜索、筛选 -->
            <header class="auto-height padding-bottom">
                <!-- 筛选 -->
                <div class="border radius light-background">
                    <div class="ui flex-item padding border-bottom light-border hover-background">
                        <div class="start">
                            <a-input-search
                                    v-model:value="keyword"
                                    placeholder="用户名/手机号/昵称"
                                    enter-button="搜索"
                                    @search="setKeyword"
                            />
                        </div>
                        <div class="start" v-if="listQueryParams.keyword != ''">
                            <a-button type="primary" danger @click="setKeyword('')">
                                <template #icon><i class="fa fa-close margin-right-half"></i></template>
                                清除搜索
                            </a-button>
                        </div>
                        <div class="center"></div>
                        <div class="end">
                            <a-button type="primary" @click="editUser(null)">
                                <template #icon><i class="fa fa-plus margin-right"></i></template>
                                添加账户
                            </a-button>
                        </div>
                    </div>
                    <div class="ui form">
                        <div class="border-bottom light-border ui flex-item padding-half">
                            <div class="start justify-center padding-start-half" style="height: 32px;">标签</div>
                            <div class="center">
                                <div class="ant-checkbox-list">
                                    <a-checkbox v-model:checked="label.checked" v-for="label in labels" :value="label.id" @change="changeLabels">{{ label.name }}</a-checkbox>
                                    <a-button size="small" type="dashed" class="margin-half" @click="addFilter('label')">
                                        <template #icon><i class="fa fa-plus margin-right-half"></i></template>
                                        添加标签
                                    </a-button>
                                </div>
                            </div>
                            <div class="end justify-center padding-end-half" style="height: 32px;">
                                <a href="{url url='/sso/admin/user/label-list'}">管理</a>
                            </div>
                        </div>
                        <div class="border-bottom light-border ui flex-item padding-half">
                            <div class="start justify-center padding-start-half" style="height: 32px;">分组</div>
                            <div class="center">
                                <div class="ant-checkbox-list">
                                    <a-checkbox v-model:checked="group.checked" v-for="group in groups" :value="group.id" @change="changeGroups">{{ group.name }}</a-checkbox>
                                    <a-button size="small" type="dashed" class="margin-half" @click="addFilter('group')">
                                        <template #icon><i class="fa fa-plus margin-right-half"></i></template>
                                        添加分组
                                    </a-button>
                                </div>
                            </div>
                            <div class="end justify-center padding-end-half" style="height: 32px;">
                                <a href="{url url='/sso/admin/user/group-list'}">管理</a>
                            </div>
                        </div>
                        <div class="fields padding">
                            <div class="field">
                                <label class="label text-small">账户类型</label>
                                <a-radio-group v-model:value="listQueryParams.admin" size="small" button-style="solid" @change="getList">
                                    <a-radio-button value="">全部</a-radio-button>
                                    <a-radio-button value="0">普通账号</a-radio-button>
                                    <a-radio-button value="1">管理员</a-radio-button>
                                </a-radio-group>
                            </div>
                            <div class="field">
                                <label class="label text-small">状态</label>
                                <a-radio-group v-model:value="listQueryParams.state" size="small" button-style="solid" @change="getList">
                                    <a-radio-button value="">全部</a-radio-button>
                                    <a-radio-button value="1">正常</a-radio-button>
                                    <a-radio-button value="2">待审核</a-radio-button>
                                    <a-radio-button value="3">未过审</a-radio-button>
                                    <a-radio-button value="0">已禁止</a-radio-button>
                                </a-radio-group>
                            </div>
                            <div class="field">
                                <label class="label text-small">每页数量</label>
                                <div class="">
                                    <a-radio-group v-model:value="listQueryParams.total" size="small" button-style="solid" @change="getList">
                                        <a-radio-button :value="30">30</a-radio-button>
                                        <a-radio-button :value="50">50</a-radio-button>
                                        <a-radio-button :value="100">100</a-radio-button>
                                        <a-radio-button :value="200">200</a-radio-button>
                                    </a-radio-group>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </header>
            <!-- 主体内容区 -->
            <main class="overflow-hidden flex-column">
                <div class="ui table scroll-enable primary selectable" v-if="list.rows > 0">
                    <!-- 表格头部 -->
                    <div class="thead">
                        <div class="ui row">
                            <div class="col"v-for="column in columns" :class="{ 'auto-width':!column.width }" :style="column.width ? ('width:' + column.width) : null">{{ column.title }}</div>
                        </div>
                    </div>
                    <!-- 表格内容 -->
                    <div class="tbody">
                        <div class="ui row" v-for="(item, index) in list.list">
                            <div class="col justify-center" v-for="column in columns" :class="{ 'auto-width':!column.width }" :style="column.width ? ('width:' + column.width) : null">
                                <!-- 资料 -->
                                <template v-if="column.key === 'info'">
                                    <div class="ui flex-item">
                                        <div class="start">
                                            <a-popover title="头像" placement="right">
                                                <template #content>
                                                    <a-button @click="setFace(index)">修改头像</a-button>
                                                    <a-button v-if="item.face != null && item.face != ''" class="margin-left" @click="viewImage(item.face, item.nickname)">查看大图</a-button>
                                                </template>
                                                <a-avatar style="cursor: pointer;" :size="48" shape="square" :src="item.face"></a-avatar>
                                            </a-popover>
                                        </div>
                                        <div class="center">
                                            <div class=""><i class="fa-regular fa-at margin-right-half"></i> {{ item.nickname || '未设置昵称' }}</div>
                                            <div class="padding-top-half">
                                                <a-tooltip title="手机号码">
                                                    <a-tag class="margin-right-half margin-bottom-half">
                                                        <template #icon><i class="fa fa-mobile-screen margin-right"></i> </template>
                                                        <template v-if="item.phone != null && item.phone != ''">(+{{ item.countryCode }}) {{ item.phone }}</template>
                                                        <template v-else>未设置手机号码</template>
                                                    </a-tag>
                                                </a-tooltip>
                                                <a-tooltip title="用户名">
                                                    <a-tag class="margin-right-half margin-bottom-half">
                                                        <template #icon><i class="fa-regular fa-user margin-right"></i> </template>
                                                        <template v-if="item.username != null && item.username != ''">{{ item.username }}</template>
                                                        <template v-else>未设置用户名</template>
                                                    </a-tag>
                                                </a-tooltip>
                                            </div>
                                            <div>
                                                <a-tag class="margin-right-half margin-bottom-half" v-if="item.state != 1 && item.state != 0" color="red">{{ item.state == 2 ? '待审核' : (item.state == 3 ? '审核未通过' : '已禁用')}}</a-tag>
                                                <a-tag class="margin-right-half margin-bottom-half" v-if="item.admin == 1" color="orange">管理员</a-tag>
                                                <a-tag class="margin-right-half margin-bottom-half" v-for="group in convertFilter('groups', item.groups)" color="pink">{{ group.name }}</a-tag>
                                                <a-tag class="margin-right-half margin-bottom-half" v-for="label in convertFilter('labels', item.labels)" color="blue">{{ label.name }}</a-tag>
                                                <a-tag class="margin-right-half margin-bottom-half button dashed" @click="setUserFilter(item)">
                                                    <i class="fa fa-gear"></i>
                                                    标签/分组设置
                                                </a-tag>
                                            </div>
                                            <div class="padding-top text-small danger-text" v-if="item.state == 0"><i class="fa-regular fa-arrow-up"></i> 该账户已被禁用</div>
                                        </div>
                                    </div>
                                </template>
                                <!-- 状态 -->
                                <template v-else-if="column.key === 'state'">
                                    <a-dropdown>
                                        <template #overlay>
                                            <a-menu @click="setState">
                                                <a-menu-item key="1" :data-index="index"><i class="fa fa-check"></i> 账户正常</a-menu-item>
                                                <a-menu-item key="2" :data-index="index"><i class="fa fa-circle-pause"></i> 等待审核</a-menu-item>
                                                <a-menu-item key="3" :data-index="index"><i class="fa fa-circle-stop"></i> 审核未通过</a-menu-item>
                                                <a-menu-item key="0" :data-index="index"><i class="fa fa-ban"></i> 禁用账户</a-menu-item>
                                            </a-menu>
                                        </template>
                                        <div class="ui flex-item border radius light-background margin-right" style="padding: 8px;">
                                            <div class="start">
                                                <i v-if="item.state == 1" class="fa fa-check"></i>
                                                <i v-else-if="item.state == 2" class="fa fa-circle-pause"></i>
                                                <i v-else-if="item.state == 3" class="fa fa-circle-stop"></i>
                                                <i v-else class="fa fa-ban"></i>
                                            </div>
                                            <div class="center">{{ item.state == 1 ? "账户正常" : (item.state == 2 ? "待审核" : (item.state == 3 ? "未通过" : "已禁止")) }}</div>
                                            <div class="end">
                                                <i class="fa fa-angle-down"></i>
                                            </div>
                                        </div>
                                    </a-dropdown>
                                </template>
                                <template v-else-if="column.key === 'parent'">
                                    <template v-if="item.parentUid > 0">
                                        <div class=""><i class="fa-regular fa-user"></i> {{ item.parentUsername || '未设置用户名' }}</div>
                                        <div class="padding-top-half"><i class="fa fa-mobile-screen"></i> (+{{ item.parentCountryCode }}){{ item.parentPhone || '未设置手机号码' }}</div>
                                        <div class="padding-top-half"><i class="fa-regular fa-at"></i> {{ item.parentNickname || '未设置昵称' }}</div>
                                    </template>
                                    <template v-else>
                                        -
                                    </template>
                                </template>
                                <template v-else-if="column.key === 'action'">
                                    <a-button type="primary" size="small" @click="editUser(item)">修改资料</a-button>
                                    <a-button class="margin-top" size="small" @click="setPassword(item)">修改密码</a-button>
                                </template>
                                <template v-else-if="column.dataIndex !== undefined">
                                    {{ item[column.dataIndex] || '' }}
                                </template>
                            </div>
                        </div>
                    </div>
                    <!-- 表格底部 -->
                    <div class="tfoot padding" v-if="list.pages > 1">
                        {include "INC_page.html"}
                    </div>
                </div>
                <div class="empty-content" v-else>
                    <a-empty :image="simpleImage" description="没有匹配到用户数据">
                        <div class="padding-top"></div>
                        <a-button type="primary">
                            <template #icon><i class="fa fa-plus"></i></template>
                            添加新用户
                        </a-button>
                    </a-empty>
                </div>
            </main>
        </div>
        <!-- 标签/分组添加 -->
        <a-modal
                v-model:visible="filter.edit"
                :title="filter.type === 'label' ? '添加标签' : '添加分组(可用于权限分配)'"
                :confirm-loading="filter.saveLoading"
                cancel-text="取消"
                ok-text="保存"
                @ok="saveFilter">
            <a-input type="text" id="filterName" v-model:value="filter.name" placeholder="填写名称，按Enter可保存！" :maxlength="20" @keyup.enter="saveFilter"/>
        </a-modal>
        <!-- 标签/分组设置 -->
        <a-modal
                v-model:visible="userFilter.edit"
                title="用户标签和分组设置(都统一保存)"
                :confirm-loading="userFilter.saveLoading"
                cancel-text="取消"
                ok-text="保存"
                @ok="saveUserFilter">
            <div class="text-center">
                <a-avatar :size="48" shape="square" :src="userFilter.user.face"></a-avatar>
            </div>
            <div class="text-center padding-top">
                <a-tag v-if="userFilter.user.phone != null && userFilter.user.phone != ''">
                    <template #icon><i class="fa fa-mobile-screen"></i></template>
                    (+{{ userFilter.user.countryCode }}){{ userFilter.user.phone }}
                </a-tag>
                <a-tag v-if="userFilter.user.username != null && userFilter.user.username != ''">
                    <template #icon><i class="fa-regular fa-user"></i></template>
                    {{ userFilter.user.username }}
                </a-tag>
                <a-tag v-if="userFilter.user.nickname != null && userFilter.user.nickname != userFilter.user.phone">
                    <template #icon><i class="fa-regular fa-at"></i></template>
                    {{ userFilter.user.nickname }}
                </a-tag>
            </div>
            <div class="text-center padding-top" v-if="userFilter.user.admin == 1">
                <a-tag style="margin: 0;" color="orange">管理员</a-tag>
            </div>
            <a-divider orientation="left" orientation-margin="0px">标签</a-divider>
            <div class="ant-checkbox-list">
                <a-checkbox v-for="label in userFilter.labels" :value="label.id" v-model:checked="label.checked">{{ label.name }}</a-checkbox>
            </div>
            <a-divider orientation="left" orientation-margin="0px">分组</a-divider>
            <div class="ant-checkbox-list">
                <a-checkbox v-for="group in userFilter.groups" :value="group.id" v-model:checked="group.checked">{{ group.name }}</a-checkbox>
            </div>
        </a-modal>
        <!-- 账号编辑、添加 -->
        <a-modal
                v-model:visible="user.edit"
                :title="user.info.uid > 0 ? '修改账户资料' : '添加新账户'"
                :confirm-loading="user.saveLoading"
                cancel-text="取消"
                ok-text="保存"
                @ok="saveUser">
            <!-- 其它字段 -->
            <div class="ui form">
                <div class="field">
                    <div class="label">账户类型</div>
                    <div class="">
                        <a-radio-group v-model:value="user.info.admin" button-style="solid">
                            <a-radio value="0">普通账号</a-radio>
                            <a-radio value="1">管理员</a-radio>
                        </a-radio-group>
                    </div>
                </div>
                <div class="field">
                    <div class="label">用户名</div>
                    <div class="">
                        <a-input v-model:value="user.info.username" placeholder="用户名(唯一，不可与现有账号重复)" />
                    </div>
                </div>
                <div class="field">
                    <div class="label">手机号码</div>
                    <div class="ui flex-item">
                        <div class="start">
                            <a-select v-model:value="user.info.countryCode">
                                <a-select-option :value="cc.code.toString()" v-for="cc in countryList">+{{ cc.code }} {{ cc.cn }}</a-select-option>
                            </a-select>
                        </div>
                        <div class="center">
                            <a-input v-model:value="user.info.phone" placeholder="手机号码" />
                        </div>
                    </div>
                </div>
                <div class="field">
                    <div class="label">昵称</div>
                    <div class="">
                        <a-input v-model:value="user.info.nickname" placeholder="填写昵称" />
                    </div>
                </div>
            </div>
        </a-modal>
        <!-- 修改密码 -->
        <a-modal
                v-model:visible="showPasswordModel"
                title="账户密码设置"
                :confirm-loading="passwordSaveLoading"
                cancel-text="取消"
                ok-text="保存"
                @ok="savePassword">
            <div class="text-center">
                <a-avatar :size="48" shape="square" :src="user.info.face"></a-avatar>
            </div>
            <div class="text-center padding-top">
                <a-tag v-if="user.info.phone != null && user.info.phone != ''">
                    <template #icon><i class="fa fa-mobile-screen"></i></template>
                    (+{{ user.info.countryCode }}){{ user.info.phone }}
                </a-tag>
                <a-tag v-if="user.info.username != null && user.info.username != ''">
                    <template #icon><i class="fa-regular fa-user"></i></template>
                    {{ user.info.username }}
                </a-tag>
                <a-tag style="margin: 0;" v-if="user.info.nickname != null && user.info.nickname != user.info.phone">
                    <template #icon><i class="fa-regular fa-at"></i></template>
                    {{ user.info.nickname }}
                </a-tag>
            </div>
            <div class="text-center padding-top" v-if="user.info.admin == 1">
                <a-tag style="margin: 0;" color="orange">管理员</a-tag>
            </div>
            <div class="padding"></div>
            <div class="ui form">
                <div class="field">
                    <div class="label">设置类型</div>
                    <div class="inner">
                        <a-radio-group v-model:value="passwordType">
                            <a-radio value="login">登陆密码</a-radio>
                            <a-radio value="sp">安全操作密码</a-radio>
                        </a-radio-group>
                    </div>
                </div>
                <div class="field">
                    <div class="label">新的密码</div>
                    <div class="inner">
                        <a-input type="text" id="password" v-model:value="password" placeholder="填写新密码6~16位长度，按Enter可保存！" :maxlength="16" @keyup.enter="savePassword"/>
                    </div>
                </div>
            </div>
        </a-modal>
        <!-- 文件选择器 -->
        <a-modal class="iframe-body"
                 v-model:visible="filesModal.show"
                 :title="filesModal.title"
                 :cancel-text="filesModal.cancelText"
                 :ok-text="filesModal.okText"
                 @ok="filesManagerOk">
            <iframe class="border radius" ref="filesFrame" v-if="filesModal.show" :src="filesModal.fs + '&resize=' + filesModal.resize + '&type=' + filesModal.type + '&multi=' + (filesModal.multi ? 1 : 0)" frameborder="0" scrolling="auto" width="100%" height="100%"></iframe>
        </a-modal>
        <!-- 图片预览 -->
        <a-image :src="preview" :preview="{ visible:previewVisible, onVisibleChange: setPreviewVisible }" :alt="previewAlt" style="display: none;"></a-image>
    </a-config-provider>
</div>
<script>
    //vue app
    const { createApp } = Vue;
    const { message, Empty } = antd;
    const app = createApp({
        data() {
            return {
                config: window.appProviderConfig,
                //空图片
                simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
                //表头
                columns: [
                    { title:"用户资料", key:"info" },
                    { width:'200px', title:"推荐人", key:"parent"},
                    { width:'180px', title:"账户状态", key:"state"},
                    { width:'120px', title:"注册时间", key:"registerTime", dataIndex:"registerTime" },
                    { width:'120px', title:"IP", key:"ip", dataIndex:"ip" },
                    { width:'100px', title:"操作", key:"action" }
                ],
                //数据
                list: {
                    rows: 0,
                    page: 1,
                    pages: 0,
                    list: []
                },
                //列表参数
                keyword: '',
                listQueryParams: {
                    state: '',
                    admin: '',
                    groups: '{$get.groups|default:""}',
                    binds: '',
                    labels: '',
                    keyword: '',
                    page: 1,
                    total: 100
                },
                //辅助数据
                groups: [],
                labels: [],
                //添加标签、分组
                filter: {
                    type: 'label',
                    name: '',
                    saveLoading: false,
                    edit: false
                },
                //用户标签/分组编辑
                userFilter: {
                    edit: false,
                    saveLoading: false,
                    type: 'label',
                    //值
                    user: {},
                    labels: [],
                    groups: []
                },
                //正在编辑的用户信息
                user: {
                    edit: false,
                    saveLoading: false,
                    info: {}
                },
                //国家代码
                countryList: [],
                //
                showPasswordModel: false,
                passwordSaveLoading: false,
                password: '',
                passwordType: 'login',
                //文件管理器
                filesModal: {
                    show: false,
                    title: "文件选择",
                    okText: "确定",
                    cancelText: "取消",
                    ok: null,
                    fs: "{url url='/fs'}?parentId=0&groupName=sso&selectable=1",
                    resize: "",
                    type: "all",
                    multi: false
                },
                //头像图片预览
                previewVisible: false,
                preview: null,
                previewAlt: null
            }
        },
        mounted() {
            //挂载成功
            this.initData();
        },
        methods: {
            //方法
            initData: function () {
                //获取分组、标签
                this.getFilters("label");
                this.getFilters("group");
                //获取列表数据
                setTimeout(() => {
                    this.getList();
                }, 300);
            },
            getFilters: function (type) {
                let self = this;
                axios.get(["{url url='/sso/api/admin'}", type, "/list"].join("/")).then(({ data }) => {
                    if (data.error === 0) {
                        let idList = type == 'group' ? self.listQueryParams.groups : self.listQueryParams.labels;
                        idList = idList == "" || idList == null ? [] : idList.split(",");
                        let list = data.data;
                        if (idList.length > 0) {
                            list.forEach(item => {
                                item.checked = idList.indexOf(item.id.toString()) !== -1;
                            });
                        }
                        self[type + 's'] = list;
                    }
                });
            },
            //获取列表
            getList : function (){
                let self = this;
                const hide = message.loading("正在加载数据");
                axios.get("{url url='/sso/api/admin/user/list'}", {
                    params: this.listQueryParams
                }).then(({ data }) => {
                    hide();
                    if (data.error === 0) {
                        self.list = data.data;
                    } else {
                        message.error(data.message);
                    }
                }).catch(() => {
                    hide();
                    message.error("加载数据失败");
                });
            },
            //首页
            firstPage : function (){
                let page = parseInt(this.list.page);
                if(page > 1){
                    this.listQueryParams.page = 1;
                    this.getList();
                }
            },
            //上一页
            prevPage : function (){
                let page = parseInt(this.list.page);
                if(page > 1){
                    this.listQueryParams.page = page - 1;
                    this.getList();
                }
            },
            //下一页
            nextPage : function (){
                let page = parseInt(this.list.page);
                let pages = parseInt(this.list.pages);
                if(page < pages){
                    this.listQueryParams.page = page + 1
                    this.getList();
                }
            },
            //最后一页
            lastPage : function (){
                let page = parseInt(this.list.page);
                let pages = parseInt(this.list.pages);
                if(page < pages){
                    this.listQueryParams.page = pages;
                    this.getList();
                }
            },
            //设置跳到第几页
            setPage : function (page){
                page = isNaN(page) ? (page.target.value || -1) : parseInt(page);
                page = page > 0 ? page : -1;
                if(page === -1){
                    message.error('参数错误');
                } else {
                    this.listQueryParams.page = page;
                    this.getList();
                }
            },
            //设置参数，重载列表
            setListQueryParam : function (params){
                //通过替换key值的方式
                for(let key in params){
                    this.listQueryParams[key] = params[key];
                }
                this.getList();
            },
            //搜索
            setKeyword: function (value){
                if(this.listQueryParams.keyword !== value){
                    this.listQueryParams.keyword = value;
                    this.getList();
                }
                if (value === '') {
                    this.keyword = '';
                }
            },
            //清除搜索
            cleanKeyword: function (){
                this.keyword = '';
                this.listQueryParams.keyword = '';
                this.getList();
            },
            //选择labels
            changeLabels: function (_event) {
                const { checked, value } = _event.target;
                let values = this.listQueryParams.labels;
                values = values === "" || values == null ? [] : values.split(",");
                if (checked) {
                    values.push(value.toString());
                } else {
                    if (values.indexOf(value.toString()) !== -1) {
                        //移除
                        values.splice(values.indexOf(value.toString()), 1);
                    }
                }
                this.setListQueryParam({ labels: values.join(",") })
            },
            changeGroups: function (_event) {
                const { checked, value } = _event.target;
                let values = this.listQueryParams.groups;
                values = values === "" || values == null ? [] : values.split(",");
                if (checked) {
                    values.push(value.toString());
                } else {
                    if (values.indexOf(value.toString()) !== -1) {
                        //移除
                        values.splice(values.indexOf(value.toString()), 1);
                    }
                }
                this.setListQueryParam({ groups: values.join(",") })
            },
            //转换成具体的标签/分组
            convertFilter: function (name, value) {
                let idList = value == null || value === "" ? [] : value.split(",");
                if (idList.length > 0) {
                    let list = name === "labels" ? this.labels : this.groups;
                    let result = [];
                    list.map(item => {
                        if (idList.indexOf(item.id.toString()) !== -1) {
                            result.push(item);
                        }
                    });
                    return result;
                }
                return [];
            },
            //
            addFilter: function (type) {
                this.filter.type = type;
                this.filter.edit = true;
                this.filter.name = '';
            },
            saveFilter: function () {
                if (this.filter.name.toString().length < 2) {
                    return message.error("名称至少2个字符");
                }
                this.filter.saveLoading = true;
                let self = this;
                axios.post(["{url url='/sso/api/admin'}", this.filter.type, "save"].join("/"), {
                    name: this.filter.name
                }).then(({ data }) => {
                    self.filter.saveLoading = false;
                    if (data.error === 0) {
                        message.success("已保存：" + self.filter.name);
                        self.filter.name = '';
                        //重载
                        self.getFilters(self.filter.type);
                    } else {
                        message.error(data.message);
                    }
                }).catch(() => {
                    self.filter.saveLoading = false;
                    message.error("服务端繁忙");
                });
            },
            //设置个人用户的标签/分组
            setUserFilter: function (user) {
                //处理
                let userLabels = user.labels != null ? user.labels.split(",") : [];
                let userGroups = user.groups != null ? user.groups.split(",") : [];
                let labels = [], groups = [];
                this.labels.map(label => {
                    labels.push({
                        id: label.id,
                        name: label.name,
                        checked: userLabels.length > 0 && userLabels.indexOf(label.id.toString()) !== -1
                    });
                });
                this.groups.map(group => {
                    groups.push({
                        checked: userGroups.length > 0 && userGroups.indexOf(group.id.toString()) !== -1,
                        id: group.id,
                        name: group.name
                    });
                });
                //
                this.userFilter = {
                    edit: true,
                    saveLoading: false,
                    //值
                    user,
                    labels,
                    groups
                };
            },
            //保存
            saveUserFilter: function () {
                //处理数据
                let uid = this.userFilter.user.uid;
                let labels = [], groups = [];
                this.userFilter.labels.map(label => {
                    if (label.checked) {
                        labels.push(label.id);
                    }
                });
                this.userFilter.groups.map(group => {
                    if (group.checked) {
                        groups.push(group.id);
                    }
                });
                this.userFilter.saveLoading = true;
                let self = this;
                self.saveUserFilterNow(uid, "label", labels, success => {
                    if (success === true) {
                        message.success("保存标签成功");
                        self.saveUserFilterNow(uid, "group", groups, success => {
                            self.userFilter.saveLoading = false;
                            if (success === true) {
                                self.userFilter.edit = false;
                                message.success("保存分组成功");
                                self.getList();
                            } else {
                                message.error("保存分组失败：" + success);
                            }
                        });
                    } else {
                        self.userFilter.saveLoading = false;
                        message.error("保存标签失败：" + success);
                    }
                });
            },
            saveUserFilterNow: function (uid, name, value, cb) {
                axios.post("{url url='/sso/api/admin/user/setFilter'}", {
                    uid,
                    name,
                    value
                }).then(({ data }) => {
                    cb(data.error === 0 ? true : data.message);
                }).catch(() => {
                    cb("服务端繁忙");
                });
            },
            editUser: function (user) {
                user = user || {
                    uid: 0,
                    username: '',
                    phone: '',
                    nickname: '',
                    countryCode: '86',
                    face: null,
                    admin: '0',
                };
                this.user = {
                    edit: true,
                    saveLoading: false,
                    info: JSON.parse(JSON.stringify(user))
                };
                if (this.countryList.length === 0) {
                    let self = this;
                    axios.get("{url url='/sso/api/sms/countryList'}").then(({ data }) => {
                        self.countryList = data.data;
                    }).catch(() => {
                        self.countryList = [{ code:86, en:"China", cn:"中国大陆" }];
                    });
                }
            },
            saveUser: function () {
                this.user.saveLoading = true;
                let self = this;
                axios.post("{url url='/sso/api/admin/user/save'}", this.user.info).then(({ data }) => {
                    self.user.saveLoading = false;
                    if (data.error === 0) {
                        self.user.edit = false;
                        self.setListQueryParam({
                            state: '',
                            admin: '',
                            groups: '',
                            binds: '',
                            labels: '',
                            keyword: '',
                        });
                    } else {
                        message.error(data.message);
                    }
                }).catch(() => {
                    self.user.saveLoading = false;
                    message.error("服务端繁忙");
                });
            },
            //设置状态
            setState: function (_event) {
                let item = _event.item;
                let index = parseInt(item["data-index"]);
                let state = _event.key;
                if (this.list.list[index].state != state) {
                    let self = this;
                    const hide = message.loading("正在标记账号状态")
                    axios.post("{url url='/sso/api/admin/user/setState'}", { state, uid: this.list.list[index].uid }).then(({ data }) => {
                        hide();
                        if (data.error === 0) {
                            self.list.list[index].state = state;
                            message.success(data.message);
                        } else {
                            message.error(data.message);
                        }
                    }).catch(() => {
                        hide();
                        message.error("服务端繁忙");
                    });
                }
            },
            //打开设置密码的对话框
            setPassword: function (user) {
                this.user.info = user;
                this.password = '';
                this.passwordType = 'login';
                this.showPasswordModel = true;
            },
            savePassword: function () {
                if (this.password.toString().length < 6) {
                    return message.error("密码最少要有6个字符");
                }
                if (this.password.toString().length > 16) {
                    return message.error("密码最长不可超过16个字符");
                }
                this.passwordSaveLoading = true;
                let self = this;
                axios.post("{url url='/sso/api/admin/user/setPassword'}", {
                    uid: this.user.info.uid,
                    password: this.password,
                    type: this.passwordType
                }).then(({ data}) => {
                    self.passwordSaveLoading = false;
                    if (data.error === 0) {
                        self.password = '';
                        self.showPasswordModel = false;
                        message.success(data.message);
                    } else {
                        message.error(data.message);
                    }
                }).catch(() => {
                    self.passwordSaveLoading = false;
                    message.error("服务端繁忙");
                });
            },
            //打开文件管理对话框
            filesManagerOpen: function (params) {
                params = params || {};
                this.filesModal.title = params.title || "文件选择";
                this.filesModal.okText = params.okText || "确定";
                this.filesModal.cancelText = params.cancelText || "取消";
                this.filesModal.resize = params.resize || "";
                this.filesModal.type = params.type || "all";
                this.filesModal.multi = params.multi || false;
                this.filesModal.ok = params.ok || null;
                this.filesModal.show = true;
            },
            //点击确定
            filesManagerOk: function () {
                //从iFrame里边找图片
                let filesManager = this.$refs.filesFrame.contentWindow.FilesManager || {};
                if (filesManager.list) {
                    let list = [];
                    filesManager.list.map(file => {
                        if (file.checked && (this.filesModal.type === "all" || file.type === this.filesModal.type)) {
                            list.push(file);
                        }
                    });
                    console.log(list);
                    if (list.length > 0 && typeof this.filesModal.ok === "function") {
                        this.filesModal.ok(this.filesModal.multi ? list : list[0]);
                    }
                }
                //关闭文件选择框
                this.filesModal.show = false;
            },
            setFace: function (index) {
                let user = this.list.list[index];
                let self = this;
                this.filesManagerOpen({
                    title: "设置用户("+ (user.username || user.phone) +")的头像",
                    okText: "确定",
                    cancelText: "取消",
                    resize: "120x120",
                    type: "image",
                    multi: false,
                    ok: image => {
                        //保存
                        const hide = message.loading("正在保存头像");
                        axios.post("{url url='/sso/api/admin/user/setFace'}", {
                            uid: user.uid,
                            face: image.url
                        }).then(({ data }) => {
                            hide();
                            if (data.error === 0) {
                                self.list.list[index].face = image.url;
                            } else {
                                message.error(data.message);
                            }
                        }).catch(() => {
                            hide();
                            message.error("服务端繁忙");
                        });
                    }
                });
            },
            viewImage: function (src, title) {
                if (src == null || src == '') {
                    return;
                }
                this.preview = src;
                this.previewAlt = title || null;
                this.setPreviewVisible(true);
            },
            setPreviewVisible: function (value) {
                this.previewVisible = value;
            }
        }
    }).use(antd);
    //挂载
    const vm = app.mount("#app-outlet");
    //
    if (window.parent.length > 0) {
        window.parent.postMessage({
            event: "location",
            data: [
                { name:"账户管理" }
            ]
        });
    }
</script>
{include "INC_footer.html"}